# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy.http import Response
from selenium import webdriver
from scrapy.http import HtmlResponse
from selenium.webdriver.common.by import By

def get_cookies_dict():
    cookies_str = 'bid=ScCwmRvLWmY; _pk_id.100001.4cf6=c60b05da76435fd0.1709607069.; __yadk_uid=8sJSE6Dt9Br2j5IejKpIUOgLMMu4wntJ; __utmc=30149280; __utmz=30149280.1709607070.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmc=223695111; __utmz=223695111.1709607070.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ll="118282"; ap_v=0,6.0; __utma=30149280.1966215020.1709607070.1709618872.1709623995.3; __utmb=30149280.0.10.1709623995; __utma=223695111.378059494.1709607070.1709618872.1709623995.3; __utmb=223695111.0.10.1709623995; _pk_ses.100001.4cf6=1; _vwo_uuid_v2=DACF958221E3FE864F94AA8330356A0FD|4dc5c820a7ea788f455d4bc73f2c7c81'
    cookies_dict = {}
    for item in cookies_str.split('; '):
        key, value = item.split('=', maxsplit=1)
        cookies_dict[key] = value
    return cookies_dict


COOKIES_DICT = get_cookies_dict()


class SpiderSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class SpiderDownloaderMiddleware:

    def __init__(self):
        self.chrome = webdriver.Chrome()

    

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        crawler.signals.connect(s.spider_closed, signal=signals.spider_closed)
        return s
    
    
    def spider_closed(self, spider):
        self.chrome.quit()

    def process_request(self, request: Response, spider):
        self.chrome.get(request.url)
        body = self.chrome.page_source.encode('utf-8')
        return HtmlResponse(self.chrome.current_url, body=body, encoding='utf-8', request=request)

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        request.cookies = COOKIES_DICT  # 设置cookies
        # request.meta = {'proxy': ....} 设置代理
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)
